/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
    Component,
} from 'react';

import {
    View,
    Text,
    StatusBar,
    Navigator,
    BackAndroid,
    Alert,
    ToastAndroid,
    Platform,
    NetInfo,
    StyleSheet
} from 'react-native';

import {Scene, Reducer, Router, TabBar, Modal, Actions} from 'react-native-router-flux'
import { connect } from 'react-redux'
import Ionicons from 'react-native-vector-icons/Ionicons'
import CommonStyles from '../styles/common'
import Colors from '../styles/colors';
import {Focus} from '../actions/routeActions'
import {ChangeNetInfo,ChangeNetExpensiveStatus,ChangeNetConnectStatus} from '../actions/netInfoActions';
import {ChangeMainToolModalVisible,ChangeMainSelectedTab} from '../actions/appActions';
import MainContainer from './mainContainer'
import TweetsContainer from './tweetsContainer'
import UserCenterContainer from './userCenterContainer'
import LoginContainer from './loginContainer'
import LoginBindChooseContainer from './loginBindChooseContainer'
import LoginBindOpenidContainer from './loginBindOpenidContainer'
import DiscoverContainer from './discoverContainer'
import NewsDetailContainer from './newsDetailContainer'
import Drawer from '../components/drawer'
import ToolModal from '../components/toolModal'

class TabIcon extends Component {
    render(){
        var color = this.props.selected ? Colors.main_green : '#aaa';
        if(this.props.title==='')
            color = Colors.main_green;
        return (
        <View style={{flex:1, flexDirection:'column',justifyContent:'center', alignItems:'center', alignSelf:'center'}}>
            <Ionicons style={{color: color}} name={this.props.iconName} size={this.props.title===''?40:30} />
            {this.props.title===''?null:(<Text style={{color: color}}>{this.props.title}</Text>)}
        </View>
        );
    }
}

class App extends Component {        
    constructor(props) {
        super(props);
        this.state={
            drawerImage:null,
            backButtonImage:null,
        };
    }
  
    reducerCreate(params) {
        const defaultReducer = Reducer(params);
        return (state, action) => {
            if (action.type === 'focus') {
                this.props.dispatch(Focus(action.scene))
            }
            return defaultReducer(state, action);
        };
    }  
  
    componentWillMount()
    {
        if(Platform.OS==='android')
        {
            BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }
        NetInfo.addEventListener('change',this.handleConnectionInfoChange.bind(this));
        NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange.bind(this));
        //获取网络当前信息
        NetInfo.fetch().done((connectionInfo) => {
        var info=this.switchConnectionInfo(connectionInfo);
            this.props.dispatch(ChangeNetInfo(info));
        });
        //获取网络当前连接状态
        NetInfo.isConnected.fetch().then((isConnected) => {
            this.props.dispatch(ChangeNetConnectStatus(isConnected));
        });
        //获取网络当前连接计费状态
        NetInfo.isConnectionExpensive().then((isConnectionExpensive) => {
            this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive));
        }); 
        
        Ionicons.getImageSource('ios-arrow-back', 30, '#fff').then((source) => this.setState({ backButtonImage: source }));
        Ionicons.getImageSource('md-menu', 30, '#fff').then((source) => this.setState({ drawerImage: source }));
    }

    componentWillUnmount() {
        if(Platform.OS==='android')
        {
            BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid.bind(this));
        }
        NetInfo.removeEventListener('change',this.handleConnectionInfoChange.bind(this));
        NetInfo.isConnected.removeEventListener('change',this.handleConnectivityChange.bind(this));
    }
    
    handleConnectionInfoChange(connectionInfo)
    {
        var info=this.switchConnectionInfo(connectionInfo);
        this.props.dispatch(ChangeNetInfo(info));
        NetInfo.isConnectionExpensive().then((isConnectionExpensive) => {
            this.props.dispatch(ChangeNetExpensiveStatus(isConnectionExpensive));
        });
    }
    
    handleConnectivityChange(isConnected)
    {
        this.props.dispatch(ChangeNetConnectStatus(isConnected));
    }
    
    switchConnectionInfo(connectionInfo)
    {
        var netStatus='none';
        connectionInfo=connectionInfo.toLowerCase();
        switch (connectionInfo) {
          case 'wifi':          
            netStatus = 'wifi';
            break;
          case 'cell':           
          case 'mobile':
            netStatus = 'mobile';
            break;
          case 'unknown':           
            netStatus = 'unknown';
            break;                              
          default:
            netStatus = 'none';
            break;
        }
        return netStatus;
    }    

    onBackAndroid()
    {
        if(this.props.scene.name=='main'||this.props.scene.name=='tabbar'||this.props.scene.name=='tab1'||this.props.scene.name=='tab2'||this.props.scene.name=='tab3'||this.props.scene.name=='tab4'||this.props.scene.name=='tab5')
        {
            var datenow=Date.now();
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= datenow) {
                return false;
            }
            this.lastBackPressed = datenow;
            ToastAndroid.show('再次点击退出应用',ToastAndroid.SHORT);
            return true;            
        }
        else
        {
            Actions.pop();
            return true;
        }
    }
    
    onSelectTab(el) {
        if (!Actions[el.props.name]) {
        throw new Error(
            `No action is defined for name=${el.props.name} ` +
            `actions: ${JSON.stringify(Object.keys(Actions))}`);
        }
        if(el.props.name!='tab3')
        {
            Actions[el.props.name]();
            this.props.dispatch(ChangeMainSelectedTab(el.props.name));
            this.props.dispatch(ChangeMainToolModalVisible(false));
        }
        else
        {
            this.props.dispatch(ChangeMainToolModalVisible(true));
        }
    }  
  
    render() {
        return (
            this.state.backButtonImage!=null&&this.state.drawerImage!=null?
            (<View style={CommonStyles.flex1}>
            <StatusBar backgroundColor={Colors.main_green} barStyle="light-content"/>
            <Router createReducer={this.reducerCreate.bind(this)} getSceneStyle={getSceneStyle}>
                <Scene key="modal" component={Modal}>
                    <Scene key="root"
                        hideNavBar={true}
                        hideTabBar={true}
                        navigationBarStyle={CommonStyles.navBarStyle}
                        titleStyle={CommonStyles.navTitleStyle}
                        backButtonImage={this.state.backButtonImage}
                        leftButtonStyle={CommonStyles.navLeftButtonStyle}
                        >
                        <Scene key="main" title='开源中国' component={Platform.OS==='ios'?null:Drawer} initial={true} drawerImage={this.state.drawerImage} hideNavBar={true}>
                            <Scene key="tabbar" tabs={true} default='tab1' hideNavBar={true} tabBarStyle={styles.tabBarStyle}>
                                <Scene key="tab1"
                                    component={MainContainer} 
                                    title="综合" 
                                    initial={true}
                                    getTitle={()=>'开源中国'}
                                    navigationBarStyle={CommonStyles.navBarStyle} 
                                    titleStyle={CommonStyles.navTitleStyle}
                                    leftButtonIconStyle={CommonStyles.menuBarBtnIconStyle}
                                    tabStyle={styles.bottomTabStyle}
                                    drawerImage={this.state.drawerImage}                
                                    icon={TabIcon} 
                                    iconName={(Platform.OS==='android'?'md':Platform.OS)+'-list-box'}/>
                                <Scene key="tab2"
                                    component={TweetsContainer} 
                                    title="动弹"
                                    getTitle={()=>'开源中国'}
                                    navigationBarStyle={CommonStyles.navBarStyle} 
                                    titleStyle={CommonStyles.navTitleStyle}
                                    leftButtonIconStyle={CommonStyles.menuBarBtnIconStyle}
                                    tabStyle={styles.bottomTabStyle}
                                    drawerImage={this.state.drawerImage}                 
                                    icon={TabIcon} 
                                    iconName={(Platform.OS==='android'?'md':Platform.OS)+'-text'}
                                    onSelect={this.onSelectTab.bind(this)}/>
                                <Scene key="tab3"
                                    component={ToolModal}
                                    title=""
                                    getTitle={()=>'开源中国'}
                                    navigationBarStyle={CommonStyles.navBarStyle} 
                                    titleStyle={CommonStyles.navTitleStyle}
                                    leftButtonIconStyle={CommonStyles.menuBarBtnIconStyle}
                                    tabStyle={styles.bottomTabStyle}
                                    drawerImage={this.state.drawerImage}                 
                                    icon={TabIcon} 
                                    iconName={(Platform.OS==='android'?'md':Platform.OS)+'-add-circle'} 
                                    onSelect={this.onSelectTab.bind(this)}/>                             
                                <Scene key="tab4"
                                    component={DiscoverContainer} 
                                    title="发现" 
                                    getTitle={()=>'开源中国'}
                                    navigationBarStyle={CommonStyles.navBarStyle} 
                                    titleStyle={CommonStyles.navTitleStyle}
                                    leftButtonIconStyle={CommonStyles.menuBarBtnIconStyle}
                                    tabStyle={styles.bottomTabStyle}
                                    drawerImage={this.state.drawerImage}                 
                                    icon={TabIcon} 
                                    iconName={(Platform.OS==='android'?'md':Platform.OS)+'-eye'}/>                                                      
                                <Scene key="tab5" 
                                    component={UserCenterContainer}
                                    title="我"
                                    getTitle={()=>'开源中国'} 
                                    navigationBarStyle={CommonStyles.navBarStyle} 
                                    titleStyle={CommonStyles.navTitleStyle}
                                    leftButtonIconStyle={CommonStyles.menuBarBtnIconStyle}
                                    tabStyle={styles.bottomTabStyle}
                                    drawerImage={this.state.drawerImage} 
                                    icon={TabIcon} 
                                    iconName={(Platform.OS==='android'?'md':Platform.OS)+'-person'}/>
                            </Scene>
                        </Scene>
                        <Scene key="login" component={LoginContainer} title="登录" hideNavBar={false}/>
                        <Scene key="loginBindChoose" component={LoginBindChooseContainer} title="登录" hideNavBar={false}/>
                        <Scene key="loginBindOpenid" component={LoginBindOpenidContainer} title="帐号绑定" hideNavBar={false}/>
                        <Scene key="newsDetail" component={NewsDetailContainer} title="资讯详情" hideNavBar={false}/>
                    </Scene>                    
                </Scene>
            </Router>
            </View>):null
        );
    }
}

// define this based on the styles/dimensions you use
const getSceneStyle = function (/* NavigationSceneRendererProps */ props, computedProps) {
  const style = {
    flex: 1,
    backgroundColor: '#FAFAFA',
    shadowColor: null,
    shadowOffset: null,
    shadowOpacity: null,
    shadowRadius: null,
  };
  if (computedProps.isActive) {
    style.marginTop = computedProps.hideNavBar ? 0 : Platform.OS === 'ios' ? 64 : 44;
    style.marginBottom = computedProps.hideTabBar ? 0 : 50;
  }
  return style;
}

const styles = StyleSheet.create({
    bottomTabStyle:{
        paddingBottom:2
    },
    tabBarStyle:{
        backgroundColor: 'white'
    }
});

export default connect((state)=>({
        scene:state.routes.scene
    })
)(App);